import pygame
import random
from .constants import *
from .shapes import SHAPES, COLORS
from ..utils.colors import *

class Tetris:
    def __init__(self, config, sound_manager):
        self.config = config
        self.sound = sound_manager
        self.reset_game()
        
    def reset_game(self):
        """重置游戏状态"""
        self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
        self.current_piece = None
        self.next_piece = None
        self.current_x = 0
        self.current_y = 0
        self.current_color = None
        self.score = 0
        self.level = 1
        self.lines_cleared = 0
        self.combo_count = 0  # 连击次数
        self.game_over = False
        self.paused = False
        self.game_started = False
        # 根据难度设置初始速度
        difficulty = self.config.config.get('difficulty', 'normal')
        self.fall_speed = DIFFICULTY_LEVELS[difficulty]['fall_speed']
        self.speed_increase = DIFFICULTY_LEVELS[difficulty]['speed_increase']
        self.last_fall = pygame.time.get_ticks()
        self.new_piece()
        
    def new_piece(self):
        if self.next_piece:
            self.current_piece = self.next_piece
            self.current_color = self.next_color
        else:
            shape_idx = random.randint(0, len(SHAPES) - 1)
            self.current_piece = [row[:] for row in SHAPES[shape_idx]]
            self.current_color = COLORS[shape_idx]
            
        shape_idx = random.randint(0, len(SHAPES) - 1)
        self.next_piece = [row[:] for row in SHAPES[shape_idx]]
        self.next_color = COLORS[shape_idx]
        
        self.current_x = GRID_WIDTH // 2 - len(self.current_piece[0]) // 2
        self.current_y = 0
        
        if self.check_collision():
            self.game_over = True
            self.sound.play('gameover')
            
    def update_level(self):
        """更新等级和速度"""
        old_level = self.level
        self.level = self.lines_cleared // 10 + 1
        
        # 根据难度更新速度
        difficulty = self.config.config.get('difficulty', 'normal')
        base_speed = DIFFICULTY_LEVELS[difficulty]['fall_speed']
        speed_increase = DIFFICULTY_LEVELS[difficulty]['speed_increase']
        
        self.fall_speed = max(50, base_speed - (self.level - 1) * speed_increase)
        
        # 等级提升时播放音效
        if self.level > old_level:
            self.sound.play('levelup')
            
    def clear_lines(self):
        """消除行并计算分数"""
        lines_cleared = 0
        y = GRID_HEIGHT - 1
        while y >= 0:
            if all(cell != 0 for cell in self.grid[y]):
                lines_cleared += 1
                del self.grid[y]
                self.grid.insert(0, [0 for _ in range(GRID_WIDTH)])
            else:
                y -= 1
                
        if lines_cleared > 0:
            self.sound.play('clear')
            self.lines_cleared += lines_cleared
            self.update_level()
            
            # 基础分数
            base_scores = {
                1: SCORE_SINGLE,
                2: SCORE_DOUBLE,
                3: SCORE_TRIPLE,
                4: SCORE_TETRIS
            }
            self.score += base_scores[lines_cleared] * self.level
            
            # 连击奖励
            self.combo_count += 1
            if self.combo_count > 1:
                self.score += COMBO_BONUS * (self.combo_count - 1) * self.level
        else:
            self.combo_count = 0
            
    def move(self, dx, dy):
        """移动方块"""
        if self.paused or not self.game_started:
            return False
            
        self.current_x += dx
        self.current_y += dy
        
        if self.check_collision():
            self.current_x -= dx
            self.current_y -= dy
            
            if dy > 0:
                self.merge_piece()
                self.clear_lines()
                self.new_piece()
                return False
            return False
            
        # 计算软降得分
        if dy > 0:
            self.score += SCORE_SOFT_DROP
        
        if dx != 0:
            self.sound.play('move')
        return True
        
    def rotate(self):
        if self.paused or not self.game_started:
            return False
            
        original_piece = self.current_piece
        rows = len(self.current_piece[0])
        cols = len(self.current_piece)
        rotated = [[0 for _ in range(cols)] for _ in range(rows)]
        
        for r in range(rows):
            for c in range(cols):
                rotated[r][c] = self.current_piece[cols-1-c][r]
                
        self.current_piece = rotated
        
        if self.check_collision():
            self.current_piece = original_piece
            return False
            
        self.sound.play('rotate')
        return True
        
    def draw(self, screen):
        # 绘制游戏区边框
        pygame.draw.rect(screen, WHITE,
            (GRID_OFFSET_X - 2, GRID_OFFSET_Y - 2,
             GRID_WIDTH * BLOCK_SIZE + 4,
             GRID_HEIGHT * BLOCK_SIZE + 4), 2)
             
        # 绘制网格和方块
        for y in range(GRID_HEIGHT):
            for x in range(GRID_WIDTH):
                pygame.draw.rect(screen, GRAY, 
                    (GRID_OFFSET_X + x * BLOCK_SIZE, 
                     GRID_OFFSET_Y + y * BLOCK_SIZE, 
                     BLOCK_SIZE, BLOCK_SIZE), 1)
                     
                if self.grid[y][x]:
                    self._draw_block(screen, x, y, self.grid[y][x])
                    
        # 绘制当前方块
        if self.current_piece and not self.paused:
            for y, row in enumerate(self.current_piece):
                for x, cell in enumerate(row):
                    if cell:
                        self._draw_block(screen, 
                            self.current_x + x,
                            self.current_y + y,
                            self.current_color)
                            
        # 绘制下一个方块预览
        if self.next_piece:
            # 计算预览区域位置 (调整到右侧更合适的位置)
            preview_x = GRID_OFFSET_X + (GRID_WIDTH + 2) * BLOCK_SIZE
            preview_y = GRID_OFFSET_Y + 2 * BLOCK_SIZE
            
            # 绘制预览区标题
            font = self._get_font(24)
            title = font.render('下一个:', True, WHITE)
            screen.blit(title, (preview_x, preview_y - 30))
            
            # 绘制预览区域边框
            preview_box_size = 6 * BLOCK_SIZE
            pygame.draw.rect(screen, WHITE,
                (preview_x - BLOCK_SIZE, preview_y - BLOCK_SIZE,
                 preview_box_size, preview_box_size), 2)
            
            # 计算预览方块的中心位置
            piece_width = len(self.next_piece[0])
            piece_height = len(self.next_piece)
            
            # 居中显示预览方块
            start_x = preview_x + (preview_box_size - piece_width * BLOCK_SIZE) // 2 - BLOCK_SIZE
            start_y = preview_y + (preview_box_size - piece_height * BLOCK_SIZE) // 2 - BLOCK_SIZE
            
            # 绘制预览方块
            for y, row in enumerate(self.next_piece):
                for x, cell in enumerate(row):
                    if cell:
                        pygame.draw.rect(screen, self.next_color,
                            (start_x + x * BLOCK_SIZE + 1,
                             start_y + y * BLOCK_SIZE + 1,
                             BLOCK_SIZE - 2, BLOCK_SIZE - 2))
                        
                        # 添加高光和阴影效果
                        lighter = tuple(min(c + 50, 255) for c in self.next_color)
                        pygame.draw.line(screen, lighter,
                            (start_x + x * BLOCK_SIZE + 1,
                             start_y + y * BLOCK_SIZE + 1),
                            (start_x + x * BLOCK_SIZE + BLOCK_SIZE - 2,
                             start_y + y * BLOCK_SIZE + 1))
                        pygame.draw.line(screen, lighter,
                            (start_x + x * BLOCK_SIZE + 1,
                             start_y + y * BLOCK_SIZE + 1),
                            (start_x + x * BLOCK_SIZE + 1,
                             start_y + y * BLOCK_SIZE + BLOCK_SIZE - 2))
                             
                        darker = tuple(max(c - 50, 0) for c in self.next_color)
                        pygame.draw.line(screen, darker,
                            (start_x + x * BLOCK_SIZE + BLOCK_SIZE - 2,
                             start_y + y * BLOCK_SIZE + BLOCK_SIZE - 2),
                            (start_x + x * BLOCK_SIZE + 1,
                             start_y + y * BLOCK_SIZE + BLOCK_SIZE - 2))
                        pygame.draw.line(screen, darker,
                            (start_x + x * BLOCK_SIZE + BLOCK_SIZE - 2,
                             start_y + y * BLOCK_SIZE + BLOCK_SIZE - 2),
                            (start_x + x * BLOCK_SIZE + BLOCK_SIZE - 2,
                             start_y + y * BLOCK_SIZE + 1))

        # 绘制游戏信息
        self._draw_info(screen)
        
    def _draw_block(self, screen, x, y, color):
        # 方块主体
        pygame.draw.rect(screen, color,
            (GRID_OFFSET_X + x * BLOCK_SIZE + 1, 
             GRID_OFFSET_Y + y * BLOCK_SIZE + 1, 
             BLOCK_SIZE - 2, BLOCK_SIZE - 2))
             
        # 高光效果
        lighter = tuple(min(c + 50, 255) for c in color)
        pygame.draw.line(screen, lighter,
            (GRID_OFFSET_X + x * BLOCK_SIZE + 1,
             GRID_OFFSET_Y + y * BLOCK_SIZE + 1),
            (GRID_OFFSET_X + x * BLOCK_SIZE + BLOCK_SIZE - 2,
             GRID_OFFSET_Y + y * BLOCK_SIZE + 1))
        pygame.draw.line(screen, lighter,
            (GRID_OFFSET_X + x * BLOCK_SIZE + 1,
             GRID_OFFSET_Y + y * BLOCK_SIZE + 1),
            (GRID_OFFSET_X + x * BLOCK_SIZE + 1,
             GRID_OFFSET_Y + y * BLOCK_SIZE + BLOCK_SIZE - 2))
             
        # 阴影效果
        darker = tuple(max(c - 50, 0) for c in color)
        pygame.draw.line(screen, darker,
            (GRID_OFFSET_X + x * BLOCK_SIZE + BLOCK_SIZE - 2,
             GRID_OFFSET_Y + y * BLOCK_SIZE + BLOCK_SIZE - 2),
            (GRID_OFFSET_X + x * BLOCK_SIZE + 1,
             GRID_OFFSET_Y + y * BLOCK_SIZE + BLOCK_SIZE - 2))
        pygame.draw.line(screen, darker,
            (GRID_OFFSET_X + x * BLOCK_SIZE + BLOCK_SIZE - 2,
             GRID_OFFSET_Y + y * BLOCK_SIZE + BLOCK_SIZE - 2),
            (GRID_OFFSET_X + x * BLOCK_SIZE + BLOCK_SIZE - 2,
             GRID_OFFSET_Y + y * BLOCK_SIZE + 1))
             
    def _get_font(self, size):
        try:
            return pygame.font.SysFont('microsoftyahei', size)
        except:
            return pygame.font.SysFont(None, size)
            
    def _draw_info(self, screen):
        font = self._get_font(36)
        small_font = self._get_font(24)
        
        # 分数
        score_text = font.render(f'分数: {self.score}', True, WHITE)
        screen.blit(score_text, (10, 10))
        
        # 最高分
        high_score_text = font.render(f'最高分: {self.config.config["high_score"]}', True, WHITE)
        screen.blit(high_score_text, (10, 50))
        
        # 等级
        level_text = font.render(f'等级: {self.level}', True, WHITE)
        screen.blit(level_text, (10, 90))
        
        # 已消除行数
        lines_text = font.render(f'消除行数: {self.lines_cleared}', True, WHITE)
        screen.blit(lines_text, (10, 130))
        
        # 游戏状态
        if not self.game_started:
            start_text = font.render('按空格键开始游戏', True, WHITE)
            text_rect = start_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
            screen.blit(start_text, text_rect)
        elif self.game_over:
            game_over_text = font.render('游戏结束！', True, RED)
            text_rect = game_over_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
            screen.blit(game_over_text, text_rect)
            
            restart_text = font.render('按空格键重新开始', True, WHITE)
            text_rect = restart_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 50))
            screen.blit(restart_text, text_rect)
        elif self.paused:
            pause_text = font.render('游戏暂停', True, WHITE)
            text_rect = pause_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
            screen.blit(pause_text, text_rect)
            
        # 操作说明
        controls = [
            '方向键左右: 移动',
            '方向键上: 旋转',
            '方向键下: 加速下落',
            '空格键: 直接下落',
            'P键: 暂停/继续'
        ]
        
        for i, text in enumerate(controls):
            control_text = small_font.render(text, True, WHITE)
            screen.blit(control_text, (10, WINDOW_HEIGHT - 150 + i * 25))

    def check_collision(self):
        # 检查碰撞
        for y, row in enumerate(self.current_piece):
            for x, cell in enumerate(row):
                if cell:
                    new_x = self.current_x + x
                    new_y = self.current_y + y
                    if (new_x < 0 or new_x >= GRID_WIDTH or 
                        new_y >= GRID_HEIGHT or 
                        (new_y >= 0 and self.grid[new_y][new_x])):
                        return True
        return False

    def merge_piece(self):
        # 将当前方块合并到网格中
        for y, row in enumerate(self.current_piece):
            for x, cell in enumerate(row):
                if cell:
                    self.grid[self.current_y + y][self.current_x + x] = self.current_color

    def is_playing(self) -> bool:
        """判断游戏是否在进行中"""
        return (self.game_started and 
                not self.game_over and 
                not self.paused)
            
    def toggle_pause(self):
        """切换暂停状态"""
        self.paused = not self.paused
    
    def start(self):
        """开始新游戏"""
        self.game_started = True
    
    def restart(self):
        """重新开始游戏"""
        self.__init__(self.config, self.sound)
        self.game_started = True

    def hard_drop(self):
        """硬降"""
        if not self.is_playing():
            return
        
        drop_distance = 0
        while self.move(0, 1):
            drop_distance += 1
        
        # 计算硬降得分
        self.score += drop_distance * SCORE_HARD_DROP
        self.sound.play('drop')

    # ... [保持原有的方法不变] ... 